import loadable from "@loadable/component";
import AuthGuard from "@/components/AuthGuard";
import { createBrowserRouter, createHashRouter, RouterProvider } from "react-router-dom";

// 定义菜单和路径
export const menus = [
    {
        path: "/",
        name: "chat",
        elementPath: "Chat",
        meta: { requiresAuth: true }
    },
    {
        path: "/register",
        name: "register",
        elementPath: "Register",
        meta: { requiresAuth: false }
    },
    {
        path: "/login",
        name: "login",
        elementPath: "Login",
        meta: { requiresAuth: false }
    },
    {
        path: "/setAvatar",
        name: "setAvatar",
        elementPath: "SetAvatar",
        meta: { requiresAuth: false }
    },
    {
        path: "*", // 通配符路由
        name: "404",
        elementPath: "404", // 404 页面组件
        meta: { requiresAuth: false }
    }
];

// 是否已认证
export function routerParse(menus, isAuthenticated = false) {
    return menus.map(menu => {
        const ComponentNode = loadable(() => import(`@/pages/${menu.elementPath}.jsx`));
        // 如果需要认证，则用 AuthGuard 包裹
        const Element = menu.meta?.requiresAuth ? (
            <AuthGuard isAuthenticated={isAuthenticated}>
                <ComponentNode />
            </AuthGuard>
        ) : (
            <ComponentNode />
        );

        const route = {
            path: menu.path,
            element: Element,
        };

        if (menu.children && menu.children.length > 0) {
            route.children = routerParse(menu.children);
        }

        return route;
    });
}

// 使用 createBrowserRouter 并添加路由
const routes = routerParse(menus, /* 是否已登录 */ false);

const router = createHashRouter(routes);

function App() {
    return <RouterProvider router={router} />;
}

export default App;
